#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""This is a simple python script to copy tagged files according to
	their artist and album names into the folder structure
	%base_folder/%artist/%album

	usage: ./autotag
	options:
		-s Scan the mp3-folder for files
	 	-a Copy the folders automatically

"""

import os, sys, random, pickle, statvfs, shutil
from tagger import *
from functions import *

def CheckForThe(artist, path):

	if artist == None: return None

	if (artist[-4:].lower() == ',the') or (artist[-5:].lower() == ', the'):
		artist = artist[:-5]

	## Firstly check if an artist already exists as The Artist
	a = 'The '+ artist.title()
	t = str(os.path.join(path, a))
	try:
		if os.path.exists(t): return a
	except TypeError:
		pass

	a = artist.title()
	o = os.path.join(path,a[4:])
	n = os.path.join(path,a)

	if (artist[:4] == 'The ') and os.path.exists(o):
		shutil.move(o,n)

	return artist

############################ MAIN PROGRAM #############################

if '-a' in sys.argv: select_automatically = True
else: select_automatically = False

if '-?' in sys.argv:
	print """usage:
	 This script moves files according to their mp3-tags into the folder structure
	 base/artist/album/track.mp3


	 options:

	 -s <folder> : folder where your mp3' s are
	 -t <folder> : folder where your mp3's shall be moved

	 """
	sys.exit(1)


if ('-s' in sys.argv):
	dbpath = '' # where the mp3 files are
	for i in range(len(sys.argv)):
		if (sys.argv[i] == '-s') and (i + 1 < len(sys.argv)):
			dbpath = sys.argv[i+1]

	tpath = None # where the are moved to
	for i in range(len(sys.argv)):
		if (sys.argv[i] == '-t') and (i + 1 < len(sys.argv)):
			tpath = sys.argv[i+1]


	if not os.path.exists(dbpath):
		print dbpath,"does not exist."
		sys.exit(1)

	if tpath:
		CreateFolder(tpath)

	if not os.path.exists(tpath):
		print tpath,"does not exist."
		sys.exit(1)

	for root, dirs, files in os.walk(dbpath):
		for f in files:
			if f.endswith('.MP3') or f.endswith('.mp3'):
				notag = False

				song = os.path.join(root, f)
				dir = os.path.dirname(song)
				dirlist = dir.split('/')

				artist, album, track, tag_exists = GetArtAlb(song)

				if not tag_exists	:
					print "Warning:",song, "has no tag"
				else:
					if (artist == None) or (artist == ''):
						print "Warning:",song, "has no proper artist tag"
					if (album == None) or (album == ''):
						print "Warning:",song, "has no proper album tag"
					if (track == None) or (track == ''):
						print "Warning:",song, "has no proper track tag"

				if album  == '': album = None
				if artist == '': artist = None

				album  = Title(album)
				artist = Title(artist)

				artist = CheckForThe(artist, tpath)

				if (album != None) and (artist != None):
					temp  = os.path.join(tpath,artist)
					name = os.path.split(song)
					apath = os.path.join(temp,album)

					print "Moving", name[1], "to",apath

					try:
						error = CreateFolder(apath)
					except: continue

					shutil.move(song, os.path.join(apath,name[1]))
					#shutil.copy(song, os.path.join(apath,name[1]))
print "ready"

